package com.visionork.android.twe.model;

import java.io.Serializable;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class Part implements Serializable, Cacheable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private String title;
	private String urlLink;
	private String youtubeID;

	@Override
	public String getKey() {
		return urlLink;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getTitle() {
		return title;
	}

	public void setUrlLink(String urlLink) {
		this.urlLink = urlLink;
	}

	public String getUrlLink() {
		return urlLink;
	}

	public void setYoutubeID(String youtubeID) {
		this.youtubeID = youtubeID;
	}

	public String getYoutubeID() {
		if (youtubeID == null) {
			try {
				Document doc = Jsoup.parse(new URL(urlLink), 5000);
				Elements elms = doc.getElementsByTag("embed");
				for (Element elm : elms) {
					if (elm.hasAttr("src")) {
						String src = elm.attr("src");
						Pattern r = Pattern
								.compile("http://www.youtube.com/v/([^\\?]*)\\?");
						Matcher m = r.matcher(src);
						if (m.find()) {
							youtubeID = m.group(1);
							break;
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		return youtubeID;
	}

}
